package com.xiamo.utils;
import cn.hutool.extra.spring.SpringUtil;
import com.tencentcloudapi.asr.v20190614.AsrClient;
import com.tencentcloudapi.asr.v20190614.models.SentenceRecognitionRequest;
import com.tencentcloudapi.asr.v20190614.models.SentenceRecognitionResponse;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.xiamo.config.GeminiProperties;
import com.xiamo.config.TencentVoiceProperties;
import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.io.FileInputStream;

import java.io.IOException;
import java.util.Base64;
import java.util.UUID;
import java.io.File;
/**
 * @Description:  腾讯云语音识别类
 * @return: String
 * @Author: dawu
 * @Date: 2024-04-08 17:01
 */

@Slf4j
@UtilityClass
public class VoiceToTextUtil {

    private final TencentVoiceProperties tencentVoiceProperties;

    static {
        tencentVoiceProperties = SpringUtil.getBean(TencentVoiceProperties.class);
    }



    public static String VoiceFileToText(String filePath) {
        String secretId = tencentVoiceProperties.getSecretId();
        String secretKey = tencentVoiceProperties.getSecretKey();
        try {
            String uuid = UUID.randomUUID().toString().replace("-", "").toLowerCase();
            Credential cred = new Credential(secretId, secretKey);
            HttpProfile httpProfile = new HttpProfile();
            httpProfile.setEndpoint("asr.tencentcloudapi.com");
            ClientProfile clientProfile = new ClientProfile();
            clientProfile.setHttpProfile(httpProfile);
            AsrClient client = new AsrClient(cred, "", clientProfile);
            SentenceRecognitionRequest req = new SentenceRecognitionRequest();
            req.setProjectId(0L);
            req.setSubServiceType(2L);
            req.setEngSerViceType("16k_zh");
            req.setSourceType(1L); // 设置为本地文件
            req.setUrl(""); // 置空 URL
            req.setVoiceFormat("mp3"); // 设置音频格式，根据实际情况修改
            req.setUsrAudioKey(uuid);

            File file = new File(filePath);
            byte[] buffer = new byte[(int) file.length()];
            req.setDataLen(file.length());
            FileInputStream inputFile = new FileInputStream(file);
            inputFile.read(buffer);
            inputFile.close();
            String encodeData = Base64.getEncoder().encodeToString(buffer);
            req.setData(encodeData);

            SentenceRecognitionResponse resp = client.SentenceRecognition(req);
            String result = resp.getResult();
            if (StringUtils.isNotBlank(result)) {
                return result;
            }
            return null;
        } catch (TencentCloudSDKException | IOException e) {
            log.error("出错,{}",e.toString());
            return null;
        }
    }
}
